package com.cvs.security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.User;
import com.cvs.DAO.*;
import com.cvs.model.*;
public class CustomUserDetailsService implements UserDetailsService {
		private ChmDAO dataService = new ChmDAOImpl();

		@Override
		public UserDetails loadUserByUsername(String username)
				throws UsernameNotFoundException, DataAccessException {
			UserDetails user = null;
			
			 try {
		        	
		        	UserEntity dbUser = dataService.searchDatabaseForUsername(username);
		            user =  new User(
		            		dbUser.getUserName(),
		            		dbUser.getPassword(),
		                    true,
		                    true,
		                    true,
		                    true,
		                    getAuthorities(dbUser.getAccessLevel()));

		        } catch (Exception e) {

		            throw new UsernameNotFoundException("Error in retrieving user");
		        }

		        return user;
		    }
			
		 public Collection<GrantedAuthority> getAuthorities(Integer access) {
		        // Create a list of grants for this user
		        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

		        // All users are granted with ROLE_USER access
		        authList.add(new GrantedAuthorityImpl("ROLE_USER"));

		        // Check if this user has admin access
		        // We interpret Integer(1) as an admin user
		        if ( access.compareTo(2) == 0) {
		            // UserEntity has admin access

		            authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		        }

		        // Return list of granted authorities
		        return authList;
		    }
		
}
